package com.zx._03_并发.chapter_06_compent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;

/**
 * 同步组件Semaphore
 */
@Slf4j
public class Demo_02_Semaphore {

    public static void main(String[] args) {
        int ThreadToatl = 100;//线程数
        final CountDownLatch downLatch = new CountDownLatch(ThreadToatl);
        int permits = 10;//允许并发的线程数
        Semaphore semaphore = new Semaphore(permits);
        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < ThreadToatl; i++) {
            pool.execute(() -> {
                try {
                    //1. 每次只申请一个许可
//					semaphore.acquire();//申请本线程执行的许可，获得许可前，线程为阻塞状态
//					Thread.sleep(1000L);
//					log.info("thread run");
//					semaphore.release();//释放一个许可
                    //2. 每次只申请多个许可
//					semaphore.acquire(3);//申请本线程执行的许可，获得许可前，线程为阻塞状态
//					Thread.sleep(1000L);
//					log.info("thread run");
//					semaphore.release(3);//释放三个许可
                    //3. 尝试获得许可
//					if(semaphore.tryAcquire()) {
//						Thread.sleep(1000L);
//						log.info("thread run");
//						semaphore.release();//释放三个许可
//					}
                    //4. 尝试获得许可,允许等待阻塞2秒钟
                    if (semaphore.tryAcquire(2, TimeUnit.SECONDS)) {
                        Thread.sleep(1000L);
                        log.info("thread run");
                        semaphore.release();//释放三个许可
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                downLatch.countDown();
            });
        }
        pool.shutdown();
        try {
            downLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        pool.shutdownNow();
    }
}
